<template>
  <span class='count-scroll'>
    {{ currentNumber }}
  </span>
</template>

<script lang='ts' setup>
import type { PropType } from 'vue';

const props = defineProps({
  number: {
    type: Number as PropType<number>,
    default: 0,
    required: true,
  },
  duration: {
    type: Number as PropType<number>,
    default: 1000,
  },
})

const currentNumber = ref(0);
const targetNumber = ref(props.number);
const animationFrameId = ref(0);
const startTime = ref(0);
const endTime = ref(0);


// 开始动画
const startAnimation = () => {
  endTime.value = startTime.value + props.duration;
  cancelAnimationFrame(animationFrameId.value);
  animationFrameId.value = requestAnimationFrame(updateNumber);
};

// 更新数字
const updateNumber = (timestamp: number) => {
  const progress = (timestamp - 100) / props.duration;
  currentNumber.value = Math.floor(targetNumber.value * Math.min(progress, 1));

  if (progress < 1) {
    animationFrameId.value = requestAnimationFrame(updateNumber);
  } else {
    currentNumber.value = targetNumber.value;
  }
};

watchEffect(() => {
  targetNumber.value = props.number;
  startAnimation();
});

</script>
<style scoped lang='scss'>
.count-scroll {
  position: relative;
  height: 100%;
  font-family: Gotham, "Helvetica Neue", Helvetica, Arial, "sans-serif";
  font-weight: bolder;
}
</style>
